package com.leyou.system.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.domain.PageResult;
import com.leyou.common.exception.domain.ExceptionEnum;
import com.leyou.common.exception.domain.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.system.domain.Permission;
import com.leyou.system.domain.Role;
import com.leyou.system.dto.PermissionDTO;
import com.leyou.system.dto.RoleDTO;
import com.leyou.system.mapper.PermissionMapper;
import com.leyou.system.mapper.RoleMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    // 注入permissionService为添加角色做准备
    @Autowired
    private PermissionService permissionService;

    /**
     * 角色分页
     * @param page
     * @param rows
     * @param key
     * @param sortBy
     * @param desc
     * @return
     */
    public PageResult<RoleDTO> rolePageQuery(Integer page, Integer rows, String key, String sortBy, boolean desc) {

        //封装分页条件
        PageHelper.startPage(page,rows);
        //创建一个封装条件的对象
        Example example = new Example(Role.class);
        //判断查询条件是否有值
        if (!StringUtils.isEmpty(key)){
            Example.Criteria criteria = example.createCriteria();
            //拿搜索关键字去模糊查询role_name名称
            criteria.orLike("name","%"+key+"%");
        }

        if (!StringUtils.isEmpty(sortBy)){
            example.setOrderByClause(sortBy+" "+(desc ? "DESC" : "ASC"));
        }

        //分页查询
        List<Role> roles = roleMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(roles)){
                throw new LyException(ExceptionEnum.ROLE_NOT_FOUND);
        }

        //封装分页对象
        PageInfo<Role> pageInfo = new PageInfo<>(roles);

        //获取分页对象List
        List<Role> list = pageInfo.getList();
        //转成dto的集合
        List<RoleDTO> roleDTOS = BeanHelper.copyWithCollection(list, RoleDTO.class);
        //封装自定义的分页对象
        PageResult<RoleDTO> pageResult = new PageResult<>(pageInfo.getTotal(), pageInfo.getPages(), roleDTOS);

        return pageResult;

    }

    /**
     * 根据ID查找角色
     * @param id
     * @return
     */
    public RoleDTO findRoleById(String id) {
        Role role = roleMapper.selectByPrimaryKey(id);

        return BeanHelper.copyProperties(role,RoleDTO.class);
    }

    /**
     * 新增角色
     * @param roleName
     * @param roleDesc
     * @param pids
     */
    public void saveRole(String roleName, String roleDesc, List<Integer> pids) {
        //保存角色
        Role role = new Role();
        role.setRoleName(roleName);
        role.setRoleDesc(roleDesc);
        role.setCreateTime(new Date());
        int count = roleMapper.insertSelective(role);
        if (count != 1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        // 更新角色权限关联表
        count = roleMapper.insertRolePermission(role.getId(), pids);
        if (count != pids.size()){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    /**
     * 查询所有的角色
     * @return
     */
    public List<RoleDTO> findAllRole() {
        List<Role> roles = roleMapper.selectAll();
        List<RoleDTO> list = BeanHelper.copyWithCollection(roles, RoleDTO.class);
        return list;
    }

    /**
     * 更新角色
     * @param id
     * @param roleName
     * @param roleDesc
     */
    public void updateRole(Integer id, String roleName, String roleDesc, List<Integer> pids) {
        Role role = roleMapper.selectByPrimaryKey(id);
        if (role.equals(null)){

            throw new LyException(ExceptionEnum.ROLE_NOT_FOUND);
        }
        role.setRoleName(roleName);
        role.setRoleDesc(roleDesc);
        role.setUpdateTime(new Date());
        int i = roleMapper.updateByPrimaryKey(role);
        if (i!=1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        //删除旧权限
        roleMapper.countPermissionByRoleId(id);
        int count = roleMapper.deleteRolePermission(id);
        //绑定新权限
        roleMapper.insertRolePermission(id, pids);
    }

    /**
     * 删除角色
     * @param id
     */
    public void deleteRoleById(Integer id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        if (role.equals(null)){

            throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }

        //删除角色权限关联表
        int i = roleMapper.countPermissionByRoleId(id);
        int count = roleMapper.deleteRolePermission(id);
        if (i != count){
            throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }

        //删除角色用户关联表
        i = roleMapper.countUserByRoleId(id);
        count = roleMapper.deleteRoleUser(id);
        if (i != count){
            throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }

        //删除角色
        count = roleMapper.deleteByPrimaryKey(id);
        if (count != 1){
            throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }
    }

    public List<PermissionDTO> queryPermissionByRoleId(Integer rid) {

        List<Integer> pids = roleMapper.queryPidsByRid(rid);
        List<PermissionDTO> permissionDTOS = new ArrayList<>();

        pids.forEach(pid->{
            Permission permission = permissionMapper.selectByPrimaryKey(pid);
            PermissionDTO permissionDTO = BeanHelper.copyProperties(permission, PermissionDTO.class);
            permissionDTOS.add(permissionDTO);
        });
        return permissionDTOS;
    }
}
